﻿using Autofac;
using Autofac.Integration.Mvc;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using ZSZ.CommonMVC;
using ZSZ.Website.Jobs;

namespace ZSZ.Website
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            //过滤器
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            //路由
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //压缩脚本和样式表
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //自动截取空格和进行全角转换
            ModelBinders.Binders.Add(typeof(string), new TrimToDBCModelBinder());
            ModelBinders.Binders.Add(typeof(int), new TrimToDBCModelBinder());
            ModelBinders.Binders.Add(typeof(long), new TrimToDBCModelBinder());
            ModelBinders.Binders.Add(typeof(double), new TrimToDBCModelBinder());

            //从配置文件中读取log4net配置进行初始化
            log4net.Config.XmlConfigurator.Configure();

            #region IOC Autofac 配置
            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
            // 把当前程序集中的 Controller  都注册
            // 不要忘了.PropertiesAutowired() ，作用：使用别的 Service 依赖
            //获取所有相关类库的程序集
            Assembly[] assemblies = new Assembly[] { Assembly.Load("ZSZ.DAL") ,
                Assembly.Load("ZSZ.DALFactory") ,
                Assembly.Load("ZSZ.Service") };
            builder.RegisterAssemblyTypes(assemblies).Where(type => !type.IsAbstract)
            .AsImplementedInterfaces().PropertiesAutowired();

            //注册程序集下所有类
            builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).PropertiesAutowired();

            var container = builder.Build();
            // 注册系统级别的 DependencyResolver ，这样当 MVC  框架创建 Controller  等对象的时候都是管 Autofac  要对象。
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            #endregion

            //定时任务
            startQuartz();
        }
        private void startQuartz()
        {
            IScheduler sched = new StdSchedulerFactory().GetScheduler();

            //给老板的报表开始
            JobDetailImpl jdBossReport
                = new JobDetailImpl("jdBossReport", typeof(BossReportJob));
            IMutableTrigger triggerBossReport
                = CronScheduleBuilder.DailyAtHourAndMinute(23, 30).Build();//每天23:45执行一次
            triggerBossReport.Key = new TriggerKey("triggerBossReport");
            sched.ScheduleJob(jdBossReport, triggerBossReport);
            //给老板的报表结束


            sched.Start();

        }
    }
}
